//
//  GBPersonalHomepageViewController.m
//  PublicSentimentMonitorSystem
//
//  Created by 郭斌 on 15/11/7.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "GBPersonalHomepageViewController.h"
#import "UniversialTextfield.h"
#import "GBHomepageTableview.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"

@interface GBPersonalHomepageViewController ()<UITextFieldDelegate>
{
    UniversialTextfield *personalHomepageTextfield; //输入昵称的textfield
    UIButton *searchBtn; //查询按钮
    UITapGestureRecognizer *tapGestureClick; //点击手势
    UILabel *hintLabel; //提示信息的label
    UIView *view11;
    GBHomepageTableview *homepageTableview; //显示信息的tableview
    NSMutableArray *homepageArray; //用户选择的个人主页
    NSMutableArray *homepageIdArray; //用户选择的个人主页的id
}
@end

@implementation GBPersonalHomepageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WQColor(247, 249, 250);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newData2:) name:@"NewArray2" object:nil];
    
    //初始化点击手势，以判断是否点击的是除了uitextfield之外的地方
    [self createTapGesture];
    
    personalHomepageTextfield = [[UniversialTextfield alloc] initWithFrame:CGRectMake(0, 20, screenW, 35)];
    personalHomepageTextfield.backgroundColor = [UIColor whiteColor];
    personalHomepageTextfield.placeholder = @"请输入个人主页";
    personalHomepageTextfield.layer.borderColor = [UIColor lightGrayColor].CGColor;
    //键盘类型
    personalHomepageTextfield.keyboardType = UIKeyboardTypeDefault;
    //返回按钮类型
    personalHomepageTextfield.returnKeyType = UIReturnKeyDone;
    //改变输入框起始位置
    [self setTextFieldLeftPadding:personalHomepageTextfield forWidth:10];
    personalHomepageTextfield.delegate = self;
    [self.view addSubview:personalHomepageTextfield];
    
    searchBtn = [UIButton buttonWithType:0];
    //searchBtn.backgroundColor = KDColor;
    searchBtn.frame = CGRectMake(screenW - 40, 20, 40, 35);
    [searchBtn setImage:[UIImage imageNamed:@"默认添加"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchBtn];
    
    view11 = [[UIView alloc] initWithFrame:CGRectMake(0, 55, screenW, 30)];
    
    hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, screenW, 30)];
    hintLabel.textColor = [UIColor lightGrayColor];
    hintLabel.font = [UIFont systemFontOfSize:12];
    hintLabel.text = @"请输入个人主页";
    [view11 addSubview:hintLabel];
    [self.view addSubview:view11];
    
    //创建tableview
    [self CreateTableView];
    // Do any additional setup after loading the view.
}

#pragma mark - 创建tableview
-(void)CreateTableView
{
    if(homepageTableview == nil)
    {
        if(_dataArray == nil || _dataArray.count == 0)
        {
            homepageTableview = [[GBHomepageTableview alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        }
        else
        {
            homepageTableview = [[GBHomepageTableview alloc] initWithFrame:CGRectMake(0, 85, screenW, 200)];
        }
        homepageArray = [NSMutableArray arrayWithArray:_dataArray];
        homepageIdArray = [NSMutableArray arrayWithArray:_dataIdArray];
        homepageTableview.dataArray = [NSMutableArray arrayWithArray:_dataArray];
        homepageTableview.dataIdArray = [NSMutableArray arrayWithArray:_dataIdArray];
        [self.view addSubview:homepageTableview];
    }
}

#pragma mark - 删除按钮，接收新的数据(弹出界面的数据)
-(void)newData2:(NSNotification *)note
{
    NSDictionary *user = [note userInfo];
    NSMutableArray *dataArr = [user objectForKey:@"deleteArray"];
    NSMutableArray *dataIdArr = [user objectForKey:@"deleteIdArray"];
    
    homepageArray = [NSMutableArray arrayWithArray:dataArr];
    homepageIdArray = [NSMutableArray arrayWithArray:dataIdArr];
    //NSLog(@"#####1  %@", dataArr);
}

#pragma mark - 昵称中的查询操作
-(void)searchAction
{
    [personalHomepageTextfield resignFirstResponder];
    if(personalHomepageTextfield.text.length != 0)
    {
        //请求网络
        KDAccount *account = [KDAccountTool account];
        NSString *saveUrl = [NSString stringWithFormat:@"%@%@%@%@%@", ServerActionAddr, @"&method=addTheHomepage&token=",account.tokens,@"&url=",personalHomepageTextfield.text];
        //NSLog(@"%@",saveUrl);
        //请求数据
        NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:saveUrl]];
        
        AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
            NSHTTPURLResponse *response = [op response];
            NSInteger code = [response statusCode];
            if (code == 200)
            {
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
                if([jsonDict[@"info"] intValue] > 0)//|| [jsonDict[@"status"] isEqualToString:@"ok"])
                {
                    [SVProgressHUD showSuccessWithStatus:@"添加成功" maskType:SVProgressHUDMaskTypeGradient];
                    
                    NSString *Id = [NSString stringWithFormat:@"%d", [jsonDict[@"info"] intValue]];
                    
                    //将数据添加到数据数组中
                    [homepageArray insertObject:personalHomepageTextfield.text atIndex:0];
                    [homepageIdArray insertObject:Id atIndex:0];
                    
                    if(_dataArray == nil || _dataArray.count == 0)
                    {
                        homepageTableview.frame = CGRectMake(0, 85, screenW, 200);
                    }
                    homepageTableview.dataArray = [NSMutableArray arrayWithArray:homepageArray];
                    homepageTableview.dataIdArray = [NSMutableArray arrayWithArray:homepageIdArray];
                    [homepageTableview reloadData];
                }
//                //账号在别处登录
//                else if([jsonDict[@"status"] isEqualToString:@"notlogin"])
//                {
//                    [SVProgressHUD showErrorWithStatus:@"该账号已在其他地方登陆" maskType:SVProgressHUDMaskTypeGradient];
//                    
//                    KDNewfeatureController *login = [[KDNewfeatureController alloc] init];
//                    //跳转到登陆界面
//                    //设置切换风格
//                    login.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//                    //2.切换控制器
//                    [self presentViewController:login animated:YES completion:nil];
//                }
                //查询失败
                else //if ([jsonDict[@"info"] intValue] == -1)
                {
                    [SVProgressHUD showErrorWithStatus:@"添加失败" maskType:SVProgressHUDMaskTypeGradient];
                }
            }
        } failure:^(AFHTTPRequestOperation *op, NSError *error) {
            if (error) {
                //NSLog(@"req error %@",error);
                [SVProgressHUD showErrorWithStatus:@"网络请求失败" maskType:SVProgressHUDMaskTypeGradient];
            }
        }];
        [reqOper start];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"输入内容不能为空" maskType:SVProgressHUDMaskTypeGradient];
    }
}

#pragma mark - 初始化点击手势，以判断是否点击的是除了uitextfield之外的地方
-(void)createTapGesture
{
    //开启交互
    self.view.userInteractionEnabled = YES;
    tapGestureClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapClick)];
    [self.view addGestureRecognizer:tapGestureClick];
}

#pragma mark - 点击除了uitextfield之外的地方，键盘消失
-(void)TapClick
{
    if(personalHomepageTextfield.text.length == 0)
    {
        personalHomepageTextfield.placeholder = @"请输入个人主页";
    }
    [personalHomepageTextfield resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [personalHomepageTextfield resignFirstResponder];
    return YES;
}

-(void)setTextFieldLeftPadding:(UITextField *)textField forWidth:(CGFloat)leftWidth
{
    CGRect frame = textField.frame;
    frame.size.width = leftWidth;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = leftview;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self.delegateHomepage homepageReturnResult:homepageArray and:homepageIdArray];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
